package statistics

import (
	"context"
	"sale-admin/internal/app/web/service/common"
	"sale-admin/internal/define"
	"sale-admin/internal/models"
	"sort"
	"strings"

	"github.com/samber/lo"
	"gorm.io/gorm"
)

type GoodsClickStatistics struct{}

type GoodsClickReturn struct {
	YearWeek string  `json:"-"`
	Date     string  `json:"date"`
	ClickNum float64 `json:"click_num"`
}

func (gcs GoodsClickStatistics) GetGoodsClick(ctx context.Context, db *gorm.DB, merchantID string,
	startTime, endTime, salesID string, shopIDList []string, DateType int) (data []GoodsClickReturn, err error) {
	if DateType < define.HOUR || DateType > define.YEAR {
		return
	}
	common.HandlerTime(&startTime, &endTime, DateType)
	DateFormateMap := map[int]string{
		define.HOUR:  "%Y-%m-%d %H:00",
		define.DAY:   "%Y-%m-%d",
		define.WEEK:  "%Y-%m-%d",
		define.MONTH: "%Y-%m",
		define.YEAR:  "%Y",
	}
	var Result = []GoodsClickReturn{}
	field := "sum(click_num) as click_num, date_format(start_time, '" + DateFormateMap[DateType] + "') AS date"
	tx := db.Model(&models.MaGoodsClick{}).
		Where("start_time between ? and ?", startTime, endTime)
	merchantIDs, err1 := common.Order{}.GetMerchantChildren(ctx, merchantID, shopIDList)
	if err1 != nil {
		err = err1
		return
	}
	tx.Where("merchant_id in ?", merchantIDs)
	tx.Select(field).
		Group("date").
		Order("date asc").
		Find(&Result)
	FullTimeList := common.GetPeriodsByType(startTime, endTime, DateType)
	var FullTimeResult = []GoodsClickReturn{}
	for _, v := range FullTimeList {
		var dateRes = GoodsClickReturn{}
		for _, res := range Result {
			if v == res.Date {
				dateRes = res
				break
			}
		}
		dateRes.Date = v
		if DateType == define.WEEK { //按周单独处理
			dateRes.YearWeek = common.GetWeekOfYear(v)
		}
		FullTimeResult = append(FullTimeResult, dateRes)
	}
	if DateType == define.WEEK { //按周单独处理
		var WeekGoodsClickReturn []GoodsClickReturn
		var WeekResultMap = make(map[string]GoodsClickReturn)
		for _, v := range FullTimeResult {
			var item GoodsClickReturn
			if _, ok := WeekResultMap[v.YearWeek]; ok {
				item = WeekResultMap[v.YearWeek]
			}
			item.ClickNum += v.ClickNum
			item.YearWeek = v.YearWeek
			item.Date = strings.Split(v.YearWeek, "_")[0] + "年 第" + strings.Split(v.YearWeek, "_")[1] + "周"
			WeekResultMap[v.YearWeek] = item
		}
		WeekGoodsClickReturn = lo.MapToSlice(WeekResultMap, func(k string, v GoodsClickReturn) GoodsClickReturn {
			return v
		})
		sort.Slice(WeekGoodsClickReturn, func(i, j int) bool {
			return WeekGoodsClickReturn[i].YearWeek < WeekGoodsClickReturn[j].YearWeek
		})
		return WeekGoodsClickReturn, nil
	}
	return FullTimeResult, nil
}
